import os
from logger.logger import logger_handle
from lib.lib_students import process_post
from lib.lib_students import process_get
from lib.lib_students import process_put
from lib.lib_students import process_delete
from rest_framework.views import APIView
from rest_framework.response import Response
from students_management.settings import BASE_DIR
from students_management.http_config import HttpCode
from students_management.http_config import API_TEMPLATE

path = os.sep.join([BASE_DIR, 'logger', 'students.log'])
logger = logger_handle(path)


class StudentView(APIView):
    """
    学生管理
    url:/api/v1/students
    """

    def get(self, request, *args, **kwargs):
        """获取学生列表"""
        res = API_TEMPLATE.copy()
        try:
            logger.info(f"获取学生列表")
            ret = process_get(self, request)
            res.update(code=HttpCode.ok.value[0], msg=HttpCode.ok.value[1], data=ret)
        except Exception as e:
            logger.exception(f"服务器内部错误:{e}")
            res.update(code=HttpCode.internal_error.value[0], msg=HttpCode.internal_error.value[1])
        return Response(res)

    def post(self, request, *args, **kwargs):
        """增加学生"""
        res = API_TEMPLATE.copy()
        try:
            data = request.data
            resp = process_post(data)
            if not resp:
                res.update(code=HttpCode.parameter_error.value[0], msg=HttpCode.parameter_error.value[1])
            res.update(code=HttpCode.ok.value[0], msg=HttpCode.ok.value[1])
        except Exception as e:
            logger.exception(f"服务器内部错误:{e}")
            res.update(code=HttpCode.internal_error.value[0], msg=HttpCode.internal_error.value[1])
        return Response(res)

    def put(self, request, *args, **kwargs):
        """更新学生信息"""
        res = API_TEMPLATE.copy()
        try:
            data = request.data
            resp = process_put(request, data)
            if not resp:
                res.update(code=HttpCode.parameter_error.value[0], msg=HttpCode.parameter_error.value[1])
                return Response(res)
            res.update(code=HttpCode.ok.value[0], msg=HttpCode.ok.value[1])
        except Exception as e:
            logger.exception(f"服务器内部错误:{e}")
            res.update(code=HttpCode.internal_error.value[0], msg=HttpCode.internal_error.value[1])
        return Response(res)

    def delete(self, request, *args, **kwargs):
        """删除学生信息"""
        res = API_TEMPLATE.copy()
        try:
            resp = process_delete(request)
            if not resp:
                res.update(code=HttpCode.result_empty.value[0], msg=HttpCode.result_empty.value[1])
            res.update(code=HttpCode.ok.value[0], msg=HttpCode.ok.value[1])
        except Exception as e:
            logger.exception(f"服务器内部错误:{e}")
            res.update(code=HttpCode.internal_error.value[0], msg=HttpCode.internal_error.value[1])
        return Response(res)
